package cn.ffcs.businessrequest.service;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import cn.ffcs.bpm.dao.ProcessConfigDAO;
import cn.ffcs.bpm.dao.TransactProcessStatusDAO;
import cn.ffcs.bpm.dao.TransactorDAO;
import cn.ffcs.bpm.service.BizProcessManageService;
import cn.ffcs.businessrequest.dao.BusinessRequestDAO;
import cn.ffcs.businessrequest.dao.IDocContentDAO;
import cn.ffcs.businessrequest.dao.IReqDocuDAO;
import cn.ffcs.businessrequest.dao.IReqProAttachDAO;
import cn.ffcs.businessrequest.dao.IReqProgressDAO;
import cn.ffcs.businessrequest.model.BusinessRequest;
import cn.ffcs.businessrequest.model.DocContent;
import cn.ffcs.businessrequest.model.ReqDocu;
import cn.ffcs.businessrequest.model.ReqProgAttach;
import cn.ffcs.businessrequest.model.ReqProgress;
import cn.ffcs.base.service.BaseService;
import cn.ffcs.common.dao.AttachDAO;
import cn.ffcs.common.dao.IAttachDAO;
import cn.ffcs.common.model.Attach;

/**
 * 业务需求交互单服务层<br/>
 * <table>
 * <tr>
 * <td>负责人/principal:</td>
 * <td colspan="2">pany</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author pany
 * @version $Id$
 */
public class BusinessRequestService<D extends BusinessRequest> extends
        BizProcessManageService<D> implements IBusinessRequestService<D>
{
    private static final int BUFFER_SIZE = 512 * 1024;

    /** 文档DAO **/
    private IReqDocuDAO reqDocuDAO;
    
    /** 文档内容DAO **/
    private IDocContentDAO docContentDAO;
    private IReqProgressDAO<ReqProgress> reqProgressDAO;
    private IReqProAttachDAO<ReqProgAttach> reqProAttachDAO;

    private BusinessRequestDAO businessRequestDAO;

    public List findOrganized(HashMap<String, Object> conds){
        return businessRequestDAO.findOrganized(conds);
    }
    
    /**
     * 保存需求进展信息操作
     */
    @SuppressWarnings("unchecked")
    public boolean saveReqProgress(D businessRequest, List<File> uploads,
            List<String> fileNames, String[] publishIDs, String[] reqDocuIDs,
            String[] delIDs)
    {

        // 保存产品资料数据
        super.saveOrUpdate(businessRequest);

        // 保存附件
        if (uploads != null)
        {
            int i = 0;
            for (i = 0; i < uploads.size(); i++)
            {
                try
                {
                    File file = uploads.get(i);
                    byte[] result = new byte[BUFFER_SIZE];
                    result = FileUtils.readFileToByteArray(file);
                    FileUtils.forceDelete(file);

                    String fileName = fileNames.get(i);
                    String fullName = fileName;
                    String name = fullName.substring(0, fullName.indexOf("."));
                    String prefix = fullName.substring(
                            fullName.indexOf(".") + 1, fullName.length());

                    ReqDocu reqDocu = new ReqDocu();
                    DocContent doc=new DocContent();
                    doc.setContent(result);
                    docContentDAO.save(doc);
                    reqDocu.setContent(doc);
                    reqDocu.setDocType(null);
                    reqDocu.setFullName(fullName);
                    reqDocu.setName(name);
                    reqDocu.setPrefix(prefix);
                    reqDocu.setRefEntity(businessRequest.getClass().getName());
                    reqDocu.setRefEntityId(businessRequest.getId().toString());
//                    reqDocu.setIsPublish(0);// 默认为不发布
                    // 设置基本信息
                    setBaseInfo(reqDocu);

                    reqDocuDAO.save(reqDocu);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }

        // 修改附件是否为发布
        int iPub = 0;
        int iAttach = 0;
        if (publishIDs != null)
        {
            iPub = publishIDs.length;
        }
        if (reqDocuIDs != null)
        {
            iAttach = reqDocuIDs.length;
        }
        String[] unpubIDs = new String[iAttach - iPub];
        for (String pID : publishIDs)
        {
            ReqDocu reqDocu = (ReqDocu) reqDocuDAO.findById(Integer.parseInt(pID));
            reqDocuDAO.update(reqDocu);
        }
        int i = 0;
        for (String reqDocuID : reqDocuIDs)
        {
            boolean isExist = false;
            for (String pID : publishIDs)
            {
                if (reqDocuID.equalsIgnoreCase(pID))
                {
                    isExist = true;
                }
            }
            if (!isExist) unpubIDs[i++] = reqDocuID;
        }
        for (String unpubID : unpubIDs)
        {
            ReqDocu reqDocu = (ReqDocu) reqDocuDAO.findById(Integer
                    .parseInt(unpubID));
            reqDocuDAO.update(reqDocu);
        }

        // 删除附件
        if (delIDs != null && delIDs.length > 0)
        {
            for (String id : delIDs)
            {
                reqDocuDAO.deleteById(id);
            }
        }

        return true;
    }

    
    /**
     * 保存产品资料操作
     */
    @SuppressWarnings("unchecked")
    public boolean saveBusinessRequest(D businessRequest, List<File> uploads,
            List<String> fileNames, String[] publishIDs, String[] reqDocuIDs,
            String[] delIDs)
    {

        // 保存产品资料数据
        super.saveOrUpdate(businessRequest);

        // 保存附件
        if (uploads != null)
        {
            int i = 0;
            for (i = 0; i < uploads.size(); i++)
            {
                try
                {
                    File file = uploads.get(i);
                    byte[] result = new byte[BUFFER_SIZE];
                    result = FileUtils.readFileToByteArray(file);
                    FileUtils.forceDelete(file);

                    String fileName = fileNames.get(i);
                    String fullName = fileName;
                    String name = fullName.substring(0, fullName.indexOf("."));
                    String prefix = fullName.substring(
                            fullName.indexOf(".") + 1, fullName.length());

                    ReqDocu reqDocu = new ReqDocu();
                    DocContent doc=new DocContent();
                    doc.setContent(result);
                    docContentDAO.save(doc);
                    reqDocu.setContent(doc);
                    reqDocu.setDocType(null);
                    reqDocu.setFullName(fullName);
                    reqDocu.setName(name);
                    reqDocu.setPrefix(prefix);
                    reqDocu.setRefEntity(businessRequest.getClass().getName());
                    reqDocu.setRefEntityId(businessRequest.getId().toString());
//                    reqDocu.setIsPublish(0);// 默认为不发布
                    // 设置基本信息
                    setBaseInfo(reqDocu);

                    reqDocuDAO.save(reqDocu);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }


        // 删除附件
        if (delIDs != null && delIDs.length > 0)
        {
            for (String id : delIDs)
            {
                reqDocuDAO.deleteById(id);
            }
        }

        return true;
    }

    /**
     * 删除操作
     * @param baseEntity
     */
    public void remove(D businessRequest)
    {
        if (businessRequest != null)
        {
            Criterion cond1 = Restrictions.eq("refEntity", businessRequest
                    .getClass().getName());
            Criterion cond2 = Restrictions.eq("refEntityId", businessRequest
                    .getId().toString());
            Criterion condAttach = Restrictions.and(cond1, cond2);
            List<ReqDocu> reqDocus = reqDocuDAO.findBy(condAttach);
            for (ReqDocu att : reqDocus)
            {
                reqDocuDAO.deleteById(att.getId() + "");
            }
            super.remove(businessRequest);
        }
    }

    public BusinessRequestDAO getBusinessRequestDAO()
    {
        return businessRequestDAO;
    }

    public void setBusinessRequestDAO(BusinessRequestDAO businessRequestDAO)
    {
        this.businessRequestDAO = businessRequestDAO;
    }

    public IReqDocuDAO getReqDocuDAO()
    {
        return reqDocuDAO;
    }

    public void setReqDocuDAO(IReqDocuDAO reqDocuDAO)
    {
        this.reqDocuDAO = reqDocuDAO;
    }

    public IDocContentDAO getDocContentDAO()
    {
        return docContentDAO;
    }

    public void setDocContentDAO(IDocContentDAO docContentDAO)
    {
        this.docContentDAO = docContentDAO;
    }

    public IReqProgressDAO<ReqProgress> getReqProgressDAO()
    {
        return reqProgressDAO;
    }

    public void setReqProgressDAO(IReqProgressDAO<ReqProgress> reqProgressDAO)
    {
        this.reqProgressDAO = reqProgressDAO;
    }

    public IReqProAttachDAO<ReqProgAttach> getReqProAttachDAO()
    {
        return reqProAttachDAO;
    }

    public void setReqProAttachDAO(IReqProAttachDAO<ReqProgAttach> reqProAttachDAO)
    {
        this.reqProAttachDAO = reqProAttachDAO;
    }

}
